<?php

namespace App\Http\Controllers;

use App\Http\Traits\CacheTrait;
use App\Models\User;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;

class LogsController extends Controller
{
    use CacheTrait;

    public function index(Request $request)
    {
        $key_prefix = config('cache.prefix') . $this->prefix_deploy_process_log;
        $logs       = DB::table('cache')->where('key', 'like', $key_prefix . '%')->get();
        foreach ($logs as $log) {
            $key               = str_replace($key_prefix, '', $log->key);
            $info              = explode('_', $key);
            $log->user         = $info[0];
            $log->env          = $info[1];
            $log->namespace    = base64_decode($info[2], true);
            $log->triggered_at = Carbon::createFromTimestamp($log->expiration)->subMinutes($this->cache_minutes);
        }

        $collect = collect($logs);
        $sorted  = $collect->sortByDesc('triggered_at');

        return view('logs.index')->with(['logs' => $sorted]);
    }

    public function show(Request $request, $server_type, $project_namespace_base64)
    {
        $username = $request->get('user');
        if (!$username) {
            /** @var User $user */
            $user     = \Auth::user();
            $username = $user->name;
        }

        $log = $this->getDeployProcessLog($username, $server_type, $project_namespace_base64);
        $log = htmlentities(str_replace(PHP_EOL . PHP_EOL, '', preg_replace('/<f(.*)vendor(.*)/', '', $log)));

        return view('logs.show')->with(['log' => $log]);
    }
}
